package com.tan.androidtest.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2018/5/4.
 */

public class Server {


    public static void main(String[] args) {
        //ExecutorService executorService = Executors.newCachedThreadPool();
        //executorService.execute(new SocketThread());
        new Thread(new SocketThread()).start();
    }

    static class SocketThread implements Runnable {


        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(8555);
                Socket socket = serverSocket.accept();
                InetAddress inetAddress = socket.getInetAddress();
                System.out.println("有一个客服端连上了: " + inetAddress.getHostName());
                while (true) {
                    if (socket.isConnected()) {
                        //读取发送过来的数据
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String receiveMessage = reader.readLine();

                        System.out.println("客服端发过来的数据: " + receiveMessage);
                        //把发送过来的数据返给客服端
                        PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                        writer.println(receiveMessage);
                    }

                    Thread.sleep(100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
